#coding=UTF-8
import os.path
import logging
import logging.handlers

from optparse import OptionParser
from apscheduler.scheduler import Scheduler
import cherrypy
import config
import urls

version = '1.0.0'

def initLog(options):
    filename = "%s_%s" % (options.logfile, options.port)
    log_path = os.path.dirname(filename)
    if not os.path.isdir(log_path):
        os.makedirs(log_path)
    logger = logging.getLogger()
    hdlr = logging.handlers.TimedRotatingFileHandler(filename, when='midnight', backupCount=options.backupCount)
    formatter = logging.Formatter("[%(asctime)s]: %(module)s %(levelname)s %(message)s ")
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    if options.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

def main():
    parser = OptionParser(usage="usage: python %prog [options] filename",
                          version="mserver v%s" % version)
    parser.add_option("-p", "--port",
                      action="store",
                      type="int",
                      dest="port",
                      default=4444,
                      help="Listen Port")
    parser.add_option("-f", "--logfile",
                      action="store",
                      type="string",
                      dest="logfile",
                      default='./logs/run.log',
                      help="LogFile Path and Name. default=./run.log")
    parser.add_option("-n", "--backupCount",
                      action="store",
                      type="int",
                      dest="backupCount",
                      default=10,
                      help="LogFile BackUp Number")
    parser.add_option("-m", "--master",
                      action="store_true",
                      dest="master",
                      default=False,
                      help="master process")
    parser.add_option("-d", "--debug",
                          action="store_true",
                          dest="debug",
                          default=False,
                          help="debug mode")
    (options, args) = parser.parse_args()
    initLog(options)
    
    root = urls.Server()
    
    #sched = Scheduler()
    #sched.add_cron_job(urls.clear_msg, minute='*/5', second='0')
    #sched.add_cron_job(account.del_cache, minute='*/5', second='0')
    #sched.start()
    
    cherrypy.config.update({'server.socket_host':'0.0.0.0',
                        'server.socket_port':options.port,
                        'server.socket_queue_size':350,
                        'server.max_request_header_size':10 * 1024 * 1024,
                        'server.thread_pool':450,
                        'response.headers.Content-Type': 'application/json; charset=UTF-8',
                        'engine.autoreload.on':False})
    cherrypy.quickstart(root)

if __name__ == '__main__':
    main()
